package com.rom.ratethehell.protocol;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.rom.ratethehell.entities.RatePicture;



public class PictureHandler{
	private static PictureHandler instance;
	private Queue<RatePicture> pictures =  new LinkedList<RatePicture>();
	private PictureHandler() {
	}
	public static PictureHandler getInstance() {
		if (instance==null) instance = new PictureHandler();
		return instance;
	}
	public RatePicture getNextPic() throws IOException {
		synchronized (pictures) {
			if (pictures.size()<10) fillInventory();
			if ( pictures.isEmpty() )
				return RequestOrganizer.getInstance().getRandomPic();
			else  
				return pictures.poll();
		}
	}
	private void fillInventory() {
		RequestOrganizer.getInstance().getRandomPic(new ServerResponseListener<RatePicture>() {
			@Override
			public void onServerResponse(RatePicture response) {
				synchronized (pictures) {
					pictures.add(response);
					if (pictures.size()<10) fillInventory();
				}
			}
		});

	}
	public RatePicture getSpecificPic(long id) throws Exception {
		for (RatePicture p : pictures) 
			if (p.getId()==id) 
				return p;
		return RequestOrganizer.getInstance().getSpecificPic(id);
	}
	public boolean available() {
		synchronized (pictures) {
			return pictures.size()>0;
		}
	}





}
